local log = require("service.core").log.new("mysql: ")
local mysql = require("resty.mysql") --引入mysql模块

local _M = {}
_M._VERSION = '0.01'

local mt = { __index = _M }

local function is_mysql_null( res )
    if res == ngx.null then
        return true
    elseif res == nil then
        return true
    end

    return false
end

function _M.close_db(self)
    if not self.db then
        return
    end
    --释放连接(连接池实现)
    local pool_max_idle_time = self.pool_max_idle_time --最大空闲时间 毫秒
    local pool_size = self.pool_size --连接池大小

    local ok, err = self.db:set_keepalive(pool_max_idle_time, pool_size)
    if not ok then
        log.error("set keepalive error : ", err)
    end
end

function _M.query(self,queryStr)
    local res,err,errno,sqlstate = self.db:connect(self.props)
    if not res then
        log.error("connect to mysql error: ",err,"errno: ",errno,"sqlstate: ",sqlstate )
        return self:close_db()
    end
    res,err,errno,sqlstate = self.db:query(queryStr)
    if not res then
        log.error("connect to mysql error: ",err,"errno: ",errno,"sqlstate: ",sqlstate )
        return self:close_db()
    end
    if is_mysql_null(res) then
        res = {}
        log.warn("is null")
    end
    return res
end

function _M.new(self, opts)
    opts = opts or {}
    local timeout = (opts.timeout and opts.timeout * 1000) or 1000
    local pool_max_idle_time = opts.pool_max_idle_time or 60000
    local pool_size = opts.pool_size or 100
    local props = {
        host = opts.ip or '127.0.0.1',
        port = opts.port or 3306,
        database = opts.database,
        user = opts.user,
        password = opts.password,
        charset = opts.charset or "utf8"
    }
    --创建实例
    local db,err = mysql:new()
    if not db then
        ngx.say("new mysql error: ",err)
        return
    end
    -- 设置超时时间（毫秒）
    db:set_timeout(timeout)

    return setmetatable({
        db = db,
        props = props,
        pool_max_idle_time = pool_max_idle_time,
        pool_size = pool_size}, mt)
end

return _M